from google.appengine.api import memcache

from django.db import models
from djangotoolbox.fields import BlobField

from django.utils import simplejson as json

import logging

class Translator(models.Model):
    """ Model to store the trix translations for sushi_and_tears """
    content = BlobField()
    language = models.CharField(max_length=100)

    def __unicode__(self):
        return "Translator for %s" % self.language

    def get_translation(self, key):
        content = json.loads(self.content)
        string = content.get(key, u"MISSING!")
        return string

    def translate(self, key):
        """ Take a key and return the translated text in a given language """
        if not self.content:
            logging.exception("Translations are empty!")
            return ""
        translation = memcache.get("%s%s" % (self.language, key))
        if not translation:
            translation = self.get_translation(key)
            memcache.set("%s%s" % (self.language, key), translation)
        return translation